package com.simpleim.common.task;

import com.google.common.util.concurrent.*;
import com.simpleim.util.ThreadUtil;

import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * google的FutureTask
 */
public class CallableTaskScheduler {

    static ListeningExecutorService jPool;

    static {
        ThreadPoolExecutor executor = ThreadUtil.getMixedThreadPool();
        jPool = MoreExecutors.listeningDecorator(executor);
    }

    /**
     * 添加任务
     * @param task
     * @param <R>
     */
    public static <R> void add(CallbackTask<R> task) {
        ListenableFuture<R> future = jPool.submit(new Callable<R>() {
            @Override
            public R call() throws Exception {
                return task.execute();
            }
        });
        // 设置任务的回调函数
        Futures.addCallback(future, new FutureCallback<R>() {
            @Override
            public void onSuccess(R r) {
                task.onBack(r);
            }

            @Override
            public void onFailure(Throwable throwable) {
                task.onException(throwable);
            }
        });
    }
}
